package com.demo.service.impl;

import com.demo.entity.Node;
import com.demo.entity.Relation;
import com.demo.repository.NodeRepository;
import com.demo.repository.RelationRepository;
import com.demo.service.INodeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class NodeServiceImpl implements INodeService {
    @Resource
    private NodeRepository nodeRepository;
    @Resource
    private RelationRepository relationRepository;
    @Resource
    private final Session session;


    @Override
    @Transactional
    public Result executeCypherQuery(String cypherQuery, Map<String, Object> parameters) {
        return session.query(cypherQuery, parameters);
    }

    @Override
    @Transactional
    public Node save(Node node) {
        Node save = nodeRepository.save(node);
        return save;
    }

    @Override
    public List<Node> getAll() {
        List<Node> nodes = nodeRepository.selectAll();
        nodes.forEach(e -> log.info(e.toString()));
        return nodes;
    }

    @Override
    @Transactional
    public void bind(Long startNodeId, Long endNodeId, String relationName) {

        Node start = nodeRepository.findById(startNodeId).get();
        Node end = nodeRepository.findById(endNodeId).get();

        Relation relation = new Relation();
        relation.setStartNode(start);
        relation.setEndNode(end);
        relation.setRelation(relationName);

        relationRepository.save(relation);
    }
}